<style>
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
  font-size: 18px;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-row style="text-align: left;">
          <el-form-item>
            <el-input v-model="filters.rechargeNum" placeholder="充值卡编号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="filters.memberMobile" placeholder="绑定手机号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="filters.rechargeAmount" placeholder="充值卡面额"></el-input>
          </el-form-item>
        </el-row>

        <el-row style="text-align: left;">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage()"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>

          <el-form-item>
            <kt-button
              icon="fa fa-refresh"  :label="$t('action.reset')"
              @click="reset"
              type="primary"
            />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-arrow-down" label="导入" type="primary" @click="importexe" />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-download" label="模板下载" type="primary" @click="download"></kt-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o" @click="downloadExcel"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
        @handleFilterColumns="handleFilterColumns"
      ></table-column-filter-dialog>
    </div>
    <!--表格内容栏-->
    <Jic-table
      :height="350"
      :tableList="pageResult"
      :tableHeaderList="filterColumns"
      @findPage="findPage"
      :showBatchDelete="false"
      showDetailOperation
      :showDeleteOperation="false"
      :totalSize="totalSize"
      @handlePageChange="handlePageChange"
      @handleSizeChange="handleSizeChange"
      @handleDetail="handleDetail"
      :showIndex="false"
      ref="JicTable"
    ></Jic-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="20%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="100px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
        label-position="center"
        style="text-align:center"
        inline
      >
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>

        <el-row>
          <el-form-item label="充值卡面额" prop="rechargeAmount">
            <el-input
              v-model="dataForm.rechargeAmount"
              auto-complete="off"
              maxlength="5"
              onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
              show-word-limit
              :disabled="isOperat"
            ></el-input>
          </el-form-item>
          <el-form-item label="充值卡余额" prop="rechargeAmount">
            <el-input
              v-model="dataForm.rechargeAmount"
              auto-complete="off"
              maxlength="5"
              onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
              show-word-limit
              :disabled="isOperat"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="截止时间" prop="endTime">
            <el-date-picker
              v-model="dataForm.endTime"
              type="date"
              placeholder="选择日期"
              style="width:200px"
              value-format="yyyy-MM-dd HH:mm:ss"
              :disabled="isOperat"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="状态" prop="status" v-if="showStatus">
            <el-select v-model="dataForm.status" style="width: 200px;" :disabled="isOperat">
              <el-option label="待绑定" value="1">待绑定</el-option>
              <el-option label="待绑定" value="2">已绑定</el-option>
              <el-option label="待绑定" value="3">已冻结</el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
          v-show="subShow"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
    <!-- 导入modal -->
    <el-dialog
      :title="operation?'导入预览':'导入预览'"
      width="35%"
      :visible.sync="printPage"
      :close-on-click-modal="false"
    >
      <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-form-item>
            <el-upload
              ref="input"
              action="/"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="importExcel"
              type="file"
            >
              <el-button slot="trigger" icon="el-icon-upload" size="small" type="primary">上传文件</el-button>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-progress
              :text-inside="true"
              :stroke-width="26"
              :percentage="value"
              :show-text="false"
              status="exception"
            ></el-progress>
          </el-form-item>
        </el-row>
      </el-form>
      <!-- <div slot="footer" class="dialog-footer" style="text-align:center">
			<el-button :size="size" @click.native="printPage = false">{{$t('action.cancel')}}</el-button>
			<el-button :size="size" type="primary" @click.native="submitForms" :loading="editLoading">{{$t('action.comfirm')}}</el-button>
      </div>-->
    </el-dialog>
  </div>
</template>
<script src="//unpkg.com/element-ui@2.12.0/lib/index.js"></script>
<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import JicTable from "@/components/jicComponentGallery/jicTable";
import KtButton from "@/views/Core/KtButton";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { format } from "@/utils/datetime";
import XLSX from "xlsx";
import axios from "axios";
export default {
  components: {
    PopupTreeInput,
    JicTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      //状态是否展示
      showStatus: false,
      //提交按钮是否显示
      subShow: true,
      //控制是否可编辑
      isOperat: false,
      totalSize: 0,
      excelup: this.utils.getUpLoadHost(),
      size: "small",
      document_license: "",
      filters: {
        rechargeNum: "",
        memberMobile: "",
        rechargeAmount: "",
        start: "",
        limit: ""
      },
      value: 0,

      imgs: "",
      card: "",
      fileList: {},
      columns: [],
      tabJson: "",
      memberList: [],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: [],
      dialogImageUrl: "",

      operation: false, // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      printPage: false,
      dialogVisibleImage: false,
      dataFormRules: {
        rechargeAmount: [
          { required: true, message: "请输入充值卡面额", trigger: "blur" }
        ],

        endtime: [
          { required: true, message: "请输入截止时间", trigger: "blur" }
        ],
        memberId: [
          { required: true, message: "请输入使用人", trigger: "blur" }
        ],
        status: [{ required: true, message: "请输入是否调整", trigger: "blur" }]
      },
      dataForm: {},
      deptData: [],
      deptTreeProps: {
        label: "name",
        children: "children"
      },
      roles: [],
      ruleForm: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: ""
      }
    };
  },
  watch: {
    "dataForm.mobile": {
      handler(newVal, oldVal) {
        //  console.log('newVal - dataForm.mobile',this.dataForm.mobile);
        //   console.log('oldVal - dataForm.mobile',this.dataForm.mobile);
        console.log(newVal, "-----");
        this.dataForm.mobile = newVal;
        console.log(this.dataForm.mobile, "++++");
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 获取分页数据
    findPage: function(data) {
      if (data != null && data.start != null) {
        if (data.start != null) {
          this.pageRequest.pageNum = data.start;
        }
        if (data.limit != null) {
          this.pageRequest.pageSize = data.limit;
        }
      }

      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this_.utils.request.getRechargeList(this_.filters, function(res) {
        this_.pageResult = res.data.rows;
        this_.totalSize = Number(res.data.total);
      });
    },

    //导入方法
    submitForms() {},
    //详情按钮
    handleDetail(data) {
      this.dialogVisible = true;
      this.dataForm = data.row;
      this.subShow = false;
      this.isOperat = true;
      this.showStatus = true;
    },
    //左右分页点击
    handlePageChange(params) {
      // if (params != null && params.number != null) {
      //   if (params.number != null) {
      //     this.pageRequest.pageNum = params.number;
      //   }

      //   this.findPage();
      // }

      let this_ = this;
      let param = {};
      param.start = params.number;
      console.log(param, "++++++++");
      this_.utils.request.getRechargeList(param, function(res) {
        this_.pageResult = res.data.rows;
        this_.totalSize = Number(res.data.total);
      });
    },
    //切换条数变化事件
    handleSizeChange(params) {
      console.log(params, "/////");
      if (params != null && params.size != null) {
        this.pageRequest.pageSize = params.size;
      }
      this.findPage();
    },

    importExcel(file) {
      const types = file.name.split(".")[1];
      const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt"].some(
        item => item === types
      );
      if (!fileType) {
        alert("格式错误！请重新选择");
        return;
      }
      this.file2Xce(file).then(tabJson => {
        if (tabJson && tabJson.length > 0) {
          var data = {};
          var this_ = this;
          this_.card = JSON.stringify(tabJson[0].sheet);
          data.card = this_.card;
          data.t = "chargeCard";
          this.utils.request.ChargeCardUpload(data, this.backUpload);
          for (var i = 1; i <= 100; i++) {
            this.value = i;
          }
        }
      });
    },
    backUpload(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
      } else {
        this.$message({ message: "操作失败, " + data.msg, type: "error" });
      }

      this.findPage();
      this.printPage = false;
      this.value = 0;
    },
    file2Xce(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader();
        reader.onload = function(e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary"
          });
          const result = [];
          this.wb.SheetNames.forEach(sheetName => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            });
          });
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
      });
    },

    // 批量删除
    handleDelete: function(data) {
      var ids = "";
      for (var i = 0; i < data.params.length; i++) {
        ids = ids + data.params[i].id + ",";
      }
      data.t = "chargeCard";
      data.ids = ids;
      this.utils.request.deleteUserInfo(data, this.deleteInfoBack);
    }, //删除callback
    deleteInfoBack(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
      } else {
        this.$message({ message: "操作失败, ", type: "error" });
      }
      this.findPage();
    },

    //导入方法
    importexe() {
      this.printPage = true;
    },

    download() {
      //原生js下载模板
      var $form = $('<form method="GET"></form>');
      $form.attr("action", "/static/rechargeCard.xls");
      $form.appendTo($("body"));
      $form.submit();
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let filename = "库存盘点";
          this.$refs.CyTable.exportData(
            this.filters,
            this.filterColumns,
            filename
          );
        })
        .catch(() => {});
    },
    // 显示新增界面
    handleAdd: function() {
      this.isOperat = false;
      this.subShow = true;
      this.dialogVisible = true;
      this.operation = true;
      this.dataForm.id = "";
      this.dataForm = {};
    },
    // 打印
    print: function() {
      this.printPage = true;
      this.operation = true;
    },
    reset: function() {
      this.filters = {};
      this.findPage();
    },

    // 显示编辑界面
    handleEdit: function(params) {
      console.log(params);
      this.dialogVisible = true;
      this.operation = false;
      var this_ = this;
      this.$nextTick(function() {
        this_.dataForm = Object.assign({}, params.row);
      });
      var search = {};
      search.id = params.row.id;
      search.t = "chargeCard";

      this.utils.request.queryUserInfo(search, function(res) {
        if (res.code == "0000") {
        } else {
          this_.$message({ message: "获取产品信息异常", type: "error" });
        }
      });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          let this_ = this;
          this.editLoading = true;
          let params = Object.assign({}, this.dataForm);
          params.rechargeBalance = this_.dataForm.rechargeAmount;
          console.log(params);
          this.utils.request.editRechargeCard(params, this.editInfoBack);
        }
      });
    }, // 新增修改回调
    editInfoBack: function(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
      } else {
        this.$message({ message: "操作失败", type: "error" });
      }
      this.findPage();
      this.dialogVisible = false;
      this.operation = false;
      this.editLoading = false;
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      this.columns = [
        //{prop:"id", label:"ID", minWidth:50},
        { prop: "memberName", label: "使用人", minWidth: 120 },
        { prop: "memberMobile", label: "绑定手机号", minWidth: 120 },
        { prop: "rechargeNum", label: "充值卡编号", minWidth: 120 },

        {
          prop: "rechargeAmount",
          label: "充值卡面额",
          minWidth: 120,
          formatter: function(row, column, cellValue, index) {
            let realVal = "";
            if (!isNaN(cellValue) && cellValue !== "") {
              // 截取当前数据到小数点后两位
              realVal = parseFloat(cellValue).toFixed(2);
            } else {
              realVal = "--";
            }
            return realVal;
          }
        },
        {
          prop: "rechargeBalance",
          label: "充值卡余额",
          minWidth: 120,
          formatter: function(row, column, cellValue, index) {
            let realVal = "";
            if (!isNaN(cellValue) && cellValue !== "") {
              // 截取当前数据到小数点后两位
              realVal = parseFloat(cellValue).toFixed(2);
            } else {
              realVal = "--";
            }
            return realVal;
          }
        },

        { prop: "endTime", label: "截止时间", minWidth: 120 },

        {
          prop: "status",
          label: "状态",
          minWidth: 120,
          formatter: this.location
        },
        { prop: "createTime", label: "创建时间", minWidth: 120 }
      ];
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    location: function(row, column, cellValue, index) {
      if (cellValue == 1) {
        return "待绑定";
      } else if (cellValue == 2) {
        return "已绑定";
      } else if (cellValue == 3) {
        return "已冻结";
      }
    }
  },
  mounted() {
    this.findPage();
    this.initColumns();
  }
};
</script>

<style scoped>
/deep/ .el-input__inner  {
      width: 200px;
}
 .el-form-item--mini.el-form-item,
 .el-form-item--small.el-form-item  {
      margin-bottom: 10px;
}
</style>